* Clark and McCracken (2001) test
use "$datapath/Prediction_Differential.dta", clear // the 73 countries
* drop US
drop if country == "unitedstates"

keep datem country id dus_r1 dus_r*d90 dus_r dus_ln_dy dus_ln_ep 

*****************************************************************
*** ATTENTION: MANUAL CHANGES TO PRODUCE THE DESIRABLE RESULTS
*** CHANGE THE COUNTRY SAMPLE AND THE TIME SAMPLE BY COMMENTING
*** THE BELOW LINES and CHANGING THE VARIABLE "P" ACCORDINGLY

*** CHANGE THE HORIZON BY REPLACING THE VARIABLE "y"
/*
- 73 countries, 2002:01-2016:07: COMMENT COUNTRY SELECTION
- 73 countries, 2002:01-2019:02: DO NOT COMMENT ANY OF THE LINES
- 35 countries, 2002:01-2016:07: COMMENT BOTH LINES
- 35 countries, 2002:01-2019:02: COMMENT DATEM CLEANING
*/
*drop if datem > ym(2016,7)
*run "$estimpath/0_countryselection" 
gen P = 207 // 207 = 2019m2 // 175 = 2016m7 // // // number of months
gen y = dus_r1 // horizon: choose between dus_r1 dus_r12d90 dus_r24d90 dus_r36d90
*****************************************************************

* first month by country
gen month = mofd(dofm(datem))
cap drop id
sencode country, gen(id)
gen t = month - 118

*****************************************************************************
* loops
local start = 386 // January 2002 = 386

* Main 
display as text "Model 1"
forvalues j = `start'(1)592 {
	qui reghdfe y dus_r dus_ln_dy dus_ln_ep  if t <= `j', absorb(i.id , savefe) vce(cluster datem) resid
	qui predict xbplusfe_`j', xbd	
}

qui gen model1 = .
forvalues j = `start'(1)592 {
	qui replace model1 = xbplusfe_`j' if t == `j'
}
qui drop xbplusfe_*	


display as text "Model 2"
forvalues j = `start'(1)592 {
	quietly {
		bys country (datem): egen mean_`j' = mean(y)  if t <= `j'
	}
}

qui gen model2 = .
forvalues j = `start'(1)592 {
	qui replace model2 = mean_`j' if t == `j'
}

qui drop mean_*

drop if mi(model1) // drop missing observation
drop if datem < ym(2002,1) // sample selection
gen u1 = y - model1 // residual model 1
gen u2 = y - model2

gen R = 385 // in sample periods
qui ta datem

gen pi = round(P/R,.1) // use this moment to choose the critical value of 1.079 reported in Clark and McCracken (2001, Table 1).

gen numeratort = u1^2 - u1*u2
egen numerator = total(numeratort)

gen denumeratort = u2^2
egen denumerator = total(denumeratort)

gen encnew = P*numerator/denumerator

sum encnew 
* end
********************************************************